package com.diaohw.platform.framework.db.config;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.diaohw.platform.common.util.JacksonUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@MapperScan("com.diaohw.*.**.mapper")
public class DatabaseConfig {

    @PostConstruct
    public void initial() {
        ObjectMapper objectMapper = JacksonUtil.createObjectMapper();
        log.info("JacksonTypeHandler ObjectMapper is used JsonUtil.createObjectMapper()");
        JacksonTypeHandler.setObjectMapper(objectMapper);
    }

    /**
     * 添加插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        tenant(interceptor);
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); // 如果配置多个插件, 切记分页最后添加
        return interceptor;
    }

    private void tenant(MybatisPlusInterceptor interceptor) {
        try {
            TenantLineHandler beans = SpringUtil.getBean(TenantLineHandler.class);
            interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(beans));
            log.info("TenantLineHandler Bean is used TenantLineHandler");
        } catch (Exception ignore) {
        }

    }

}
